﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

//管理飞机的飞行xyz的边界
[System.Serializable]
public class Boundary
{

    public float xMin, yMin, zMin, xMax, yMax, zMax;

}

public class PlaneController : NetworkBehaviour
{

    private float normalizedSpeed;

    public float maxSpeed;
    public float maxUpDownTilt;
    public float maxLeftRightTilt;//转弯时让机身偏转用
    private Vector3 quaternion;

    public float rushSpeed;
    public float rushUpDownTilt;
    public float rushLeftRightTilt;
    public float maxRushTime;
    private bool isRush;
    private float rushTime;
    private float mspeed;
    private float mlrtilt;
    private float mudtilt;

    public float bulletSpeed, ESpeed;
    public GameObject bullet, localBullet;
    public Transform firePointL, firePointR, EPoint;
    public GameObject eraserPrefab, eraser;
    public GameObject motherBasePrefab;
    public GameObject body;
    public PlaneHp thisHp;
    private GameObject gameManager;
    public Image accelerate;
    public Text result;
    [SyncVar]
    private int playerNum;
    private Vector3 resetTransformPos;
    private Quaternion resetTransformRot;
    private bool isDead;
    private float timer;
  

    public Boundary boundary;

    private Rigidbody rb;

    public bool GetIsRush()
    {
        return this.isRush;
    }

    public bool IsDead
    {
        set
        {
            isDead = value;
        }
    }

    void Start ()
    {
        rb = GetComponent<Rigidbody>();
        thisHp = GetComponent<PlaneHp>();
        rushTime = 0;
        isRush = false;
        isDead = false;
        CmdSetMotherBase();
        if (isLocalPlayer)
        {
            GameObject.FindWithTag("MainCamera").GetComponent<Followtarget>().plane = this.transform;
            LookAt();
            quaternion = transform.rotation.eulerAngles;
            resetTransformPos = this.transform.position;
            resetTransformRot = this.transform.rotation;
            CmdAddPlayer();
        }
        gameManager = GameObject.FindWithTag("GameManager");
    }

    private void Update()
    {
        if (gameManager.GetComponent<GameManager>().IsStart)  //查看游戏是否开始和结束
        {
            CmdSendMbHp(thisHp.MotherBaseHp);
            if (thisHp.PlayerHp == 0)
            {
                isDead = true;
            }
            if (isLocalPlayer && !isDead)
            {
                Move();
                Rush();
                if (Input.GetKeyDown(KeyCode.J))
                {
                    CmdOpenFire();
                    OpenFireLocal();
                }
                if (Input.GetKeyDown(KeyCode.K) && eraser.active != false)
                {
                    eraser.SetActive(false);
                    CmdShootEraser();
                }
            }
            else if (isDead)
            {
                Deading();
            }
        }
        else
        {
            if (gameManager.GetComponent<GameManager>().hasWinner)
            {
                Debug.Log("yes");
                if (gameManager.GetComponent<GameManager>().WinnerNum == playerNum)
                {
                    result.text = "You Win!";
                }
                else
                {
                    result.text = "You Lose!";
                }
                result.color = Color.red;
                rb.velocity = Vector3.zero;
            }
        }
    }

    void Move() //普通飞行
    {
        normalizedSpeed = rb.velocity.magnitude;//把velocity换成float型
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        if (normalizedSpeed <= maxSpeed)
        {
            normalizedSpeed += Time.deltaTime * 10;
        }
        else
        {
            normalizedSpeed -= Time.deltaTime * 10;
        }
        rb.velocity = transform.forward * normalizedSpeed;
        quaternion.x = moveVertical * -maxUpDownTilt;
        quaternion.y += moveHorizontal * Time.deltaTime * maxLeftRightTilt;
        quaternion.z = moveHorizontal * -0.5f * maxLeftRightTilt;
        rb.rotation = Quaternion.Euler(quaternion);
        rb.position = new Vector3
            (Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
             Mathf.Clamp(rb.position.y, boundary.yMin, boundary.yMax),
             Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax));
    }

    void Rush() //冲刺
    {
        if (Input.GetButtonDown("Jump") && !isRush)
        {
            isRush = true;
            mspeed = maxSpeed;
            mlrtilt = maxLeftRightTilt;
            mudtilt = maxUpDownTilt;
            maxSpeed = rushSpeed;
            maxLeftRightTilt = rushLeftRightTilt;
            maxUpDownTilt = rushUpDownTilt;
        }
        else if ((Input.GetButtonDown("Jump") && isRush) || rushTime >= maxRushTime)
        {
            isRush = false;
            rushTime = 0;
            maxSpeed = mspeed;
            maxLeftRightTilt = mlrtilt;
            maxUpDownTilt = mudtilt;
            mspeed = 0;
            mlrtilt = 0;
            mudtilt = 0;
        }
        if (isRush)
        {
            rushTime += Time.deltaTime;
            //TODO GUI
        }
        RushUI();
    }

    private void Deading () //死亡计时
    {
        timer += Time.deltaTime;
        if (timer >= 5)
        {
            isDead = false;
            body.SetActive(true);
            timer = 0;
            this.transform.position = resetTransformPos;
            this.transform.rotation = Quaternion.Euler(resetTransformRot.eulerAngles);
            quaternion = transform.rotation.eulerAngles;
            CmdSetHp(100);
        }
    }

    private void RushUI() //冲刺时UI
    {
        if (isRush)
        {
            accelerate.color = Color.Lerp(accelerate.color, Color.black, 5 * Time.deltaTime);
        }
        else
        {
            accelerate.color = Color.Lerp(accelerate.color, Color.clear, 5 * Time.deltaTime);
        }
    }

    private void OnTriggerEnter(Collider other) //检测是否碰到障碍
    {
        if (other.tag == "BackGround")
        {
            isDead = true;
            rb.velocity = Vector3.zero;
            body.SetActive(false);
        }
    }

    private void OpenFireLocal() //本地模拟开火
    {
        GameObject L = Instantiate(localBullet, firePointL.position, this.transform.rotation);
        L.GetComponent<Rigidbody>().velocity = L.transform.forward * bulletSpeed;
        GameObject R = Instantiate(localBullet, firePointR.position, this.transform.rotation);
        R.GetComponent<Rigidbody>().velocity = R.transform.forward * bulletSpeed;
    }

    [Command]
    private void CmdOpenFire() //服务器发射子弹
    {
        GameObject L = Instantiate(bullet, firePointL.position, this.transform.rotation);
        L.GetComponent<Rigidbody>().velocity = L.transform.forward * bulletSpeed;
        GameObject R = Instantiate(bullet, firePointR.position, this.transform.rotation);
        R.GetComponent<Rigidbody>().velocity = R.transform.forward * bulletSpeed;
    }

    [Command]
    private void CmdShootEraser() // 服务器发射橡皮
    {
        GameObject eraser = Instantiate(eraserPrefab, EPoint.position, EPoint.rotation);
        eraser.GetComponent<Rigidbody>().velocity = this.transform.forward * ESpeed;
        NetworkServer.Spawn(eraser);
    }

    [Command]
    private void CmdSetMotherBase() //飞机创建时设置母基地
    {
        GameObject motherBase = Instantiate(motherBasePrefab, this.transform.position, this.transform.rotation);
        motherBase.GetComponent<ManageMotherBase>().player = this.gameObject;
        NetworkServer.Spawn(motherBase);
    }

    [Command]
    private void CmdAddPlayer() //向GM添加玩家数
    {
        GameObject gameManager = GameObject.Find("GameManager");
        this.playerNum = gameManager.GetComponent<GameManager>().playerNum++;
    }

    [Command]
    private void CmdSetHp(float Hp) //重生时设置飞机生命值
    {
        thisHp.PlayerHp = Hp;
    }

    [Command]
    private void CmdSendMbHp(float mbHp) //同步母基地的血量
    {
        switch (playerNum)
        {
            case 0 : GameObject.Find("GameManager").GetComponent<GameManager>().playersMbHp1 = mbHp;break;
            case 1 : GameObject.Find("GameManager").GetComponent<GameManager>().playersMbHp2 = mbHp; break;
        }
        
    }

    private void LookAt() //初始化方向
    {
        this.transform.LookAt(GameObject.Find("GameManager").transform);
    }
}